package com.xinyan.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

import static com.xinyan.zookeeper.ZkConfig.PATH;

/**
 * @author xinyan.xie
 * @description
 * @date 2020/5/15
 */
public class NodeListener {

    private static CountDownLatch watch = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        CuratorFramework build = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .namespace(PATH) //独立的命名空间，实现业务隔离
                .connectionTimeoutMs(500)
                .sessionTimeoutMs(500)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        build.start();


        String path = PATH+"/URL";
        try {
                //1. 创建一个NodeCache
                NodeCache nodeCache = new NodeCache(build, path);

                //2. 添加节点监听器
                nodeCache.getListenable().addListener(() -> {
                    ChildData childData = nodeCache.getCurrentData();
                    if(childData != null){
                        System.out.println("Path: " + childData.getPath());
                        System.out.println("Stat:" + childData.getStat());
                        System.out.println("Data: "+ new String(childData.getData()));
                    }
                });

                //3. 启动监听器
                nodeCache.start();

                //4. 返回NodeCache
            } catch (Exception e) {

            }

        System.out.println("nodeCache已开启监听模式===========监听节点："+path);
        watch.await();
        System.out.println("监听模式关闭===========");


    }
}
